-- UIChooseSpell
-- Create by huanghr
-- 选择卷轴界面

-- UIChooseSpell继承自Layer
UIChooseSpell = class("UIChooseSpell", function(equipId)
    return cc.Layer:create();
end);

function UIChooseSpell.create(equipId)
    return UIChooseSpell.new(equipId);
end

local RANK_LIST = {2, 3, 4, 5};
-- 构造函数
function UIChooseSpell:ctor(equipId)
    -- 初始化
    self:setName("UIChooseSpell");
    local node = cc.CSLoader:createNode("layout/risker_equip/ChooseSpell.csb");
    self:addChild(node);
    self.node = node;

    self.equipId = equipId;

    self.CT = node:getChildByName("CT");
    self.BT = node:getChildByName("BT");

    self.rank = 2;

    -- self:setLocalZOrder(UIMgr.BONUS_NOTIFY_ZORDER + 1);
    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    -- 注册事件回调
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 编辑各个页面的卷轴
    self:initData();

    -- 标签页
    self:redrawTabs();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 注册事件回调
function UIChooseSpell:registerEventCallback()
    -- 关注卷轴合成事件
    EventMgr.register("UIChooseSpell", event.COMPOUND_SPELL, function(args)
        self:redraw();
    end);

    -- 显示TOPMENU
    EventMgr.register("UIChooseSpell", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIChooseSpell" then
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_GEM);
            UIMgr:getCurrentScene().topMenu:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);
        end
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then

            -- 还原TopMenu的ZOrder
            local topMenu = UIMgr.getCurrentScene().topMenu;
            if topMenu then
                topMenu:setVisible(self.oldVisible);
                topMenu:setLocalZOrder(self.oldZOrder);
            end

            cclog("UIChooseSpell 界面析构清理");

            EventMgr.removeAll("UIChooseSpell");
        elseif ev == "enter" then
            -- 临时调高TOP_MENU的ZOrder
            local topMenu = UIMgr:getCurrentScene().topMenu;
            self.oldVisible = topMenu:isVisible();
            UIMgr.getCurrentScene().topMenu:setVisible(true);
            self.oldZOrder = topMenu:getLocalZOrder();
        end
    end);
end

-- 获取冈布奥数据
function UIChooseSpell:initData()
    -- 初始化
    local spells = {};

    -- 获得各阶位的卷轴ID
    for k, v in pairs(RANK_LIST) do
        spells[v] = SpellM.getSpellByRank(v);
    end

    self.spells = spells;
end

-- 绘制标签页
function UIChooseSpell:redrawTabs()
    local tabNode = findChildByName(self.node, "CT/tab");

    -- 标签页数量
    local tabNum = #RANK_LIST;

    -- 先移除旧的标签
    tabNode.rows = {};
    tabNode:removeAllChildren();

    -- 根据tab数据，生成新标签
    local widget = replaceNodeWithWidget(cc.CSLoader:createNode("layout/tab/tab.csb"));

    -- 置灰颜色
    local blendColor = TextStyleM.TEXT_COLOR_BLEND;
    local normalColor = TextStyleM.TEXT_COLOR_NORMAL;

    for i = 1, tabNum do
        local child = widget:clone();
        child:setName("tab" .. i);
        child.index = i;

        self:registerTabTouchEvent(child);

        -- 计算单元格坐标
        -- 这个坐标将是单元格的描点所在
        local x = (i - 1) * 68 + 55;
        local y = 75;

        child:setPositionX(x);
        child:setPositionY(y);

        local tabLight = findChildByName(child, "light");
        local tabImage = findChildByName(child, "tab");
        tabImage.rank = i + 1;

        tabLight:setScaleX(0.7);
        tabImage:setScaleX(0.7);

        local tabText = findChildByName(child, "text");
        local tabIcon = findChildByName(child, "icon");
        TextStyleM.setTextStyle(tabText, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
        local rankName = FormulaM.invoke("GET_ITEM_RANK_NAME", i + 1);
        tabText:setString(rankName);

        if i == 1 then
            tabLight:setVisible(true);

            tabIcon:setColor(normalColor);
            tabIcon:setVisible(false);
            tabImage:setColor(normalColor);
        else
            tabLight:setVisible(false);

            tabIcon:setColor(blendColor);
            tabIcon:setVisible(false);
            tabImage:setColor(blendColor);
        end

        tabNode:addChild(child)
        table.insert(tabNode.rows, child)
    end

    for i = 1, #tabNode.rows do
        local tab = tabNode.rows[i];
        tab:setPositionY(tab:getPositionY() + 100);
    end

    performWithDelay(self, function() self:playTabEffect(); end, 0.2);
end

-- 页签动画效果
function UIChooseSpell:playTabEffect()
    local tabNode = findChildByName(self.node, "CT/tab");
    -- 带窗口动画播放结束后，页签从上面往下掉
    for i = 1, #tabNode.rows do
        local tab = tabNode.rows[i];
        local pos = cc.p(tab:getPosition());
        local delay = cc.DelayTime:create(0.15 * (i - 1));
        local moveDown = cc.MoveTo:create(0.15, cc.p(pos.x, pos.y - 100 - 5));
        local moveBack = cc.MoveTo:create(0.15, cc.p(pos.x, pos.y - 100));
        local action = cc.Sequence:create(delay, moveDown, moveBack);
        tab:runAction(action);
    end
end

-- 注册标签页点击回调
function UIChooseSpell:registerTabTouchEvent(node)
    -- 节点
    local tabImage = node:getChildByName("tab");
    local tabLight = node:getChildByName("light");
    local tabIcon = node:getChildByName("icon");
    local tabNode = findChildByName(self.node, "CT/tab");

    -- 置灰颜色
    local blendColor = TextStyleM.TEXT_COLOR_BLEND;
    local normalColor = TextStyleM.TEXT_COLOR_NORMAL;

    local function onClick(sender, eventType)
        -- 点击时的回调
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            -- 去除其它高亮
            for i = 1, #tabNode.rows do
                tabNode.rows[i]:getChildByName("light"):setVisible(false);
                tabNode.rows[i]:getChildByName("tab"):setColor(blendColor);
                tabNode.rows[i]:getChildByName("icon"):setColor(blendColor);
            end
            -- 设置本身高亮
            tabLight:setVisible(true);
            tabImage:setColor(normalColor);
            tabIcon:setColor(normalColor);

            self.rank = sender.rank;
            self:redraw();
        end
    end

    tabImage:addTouchEventListener(onClick);
end

-- 注册点击事件
function UIChooseSpell:registerTouchEvent()
    local node = self.node;

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIChooseSpell");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end

-- 重绘
function UIChooseSpell:redraw()
    -- 绘制标题
    local titleLabel = findChildByName(self.CT, "title_label");
    local subTitle = findChildByName(self.CT, "sub_title");

    local title = ItemM.query(self.equipId, "name");

    -- 设置标题文本
    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(title);

    -- 设置副文本标题
    local subText = getLocStr("choose_compound_spell");
    TextStyleM.setSubheadStyle(subTitle);
    subTitle:setString(subText);

    -- 当前中间的图标
    local equipNode = findChildByName(self.CT, "item");

    -- 重绘当前页面，当前阶位的所有卷轴
    local spellIds = self.spells[self.rank];

    local itemNode = cc.CSLoader:createNode("layout/risker_equip/Spell.csb");
    -- 循环复用
    local widget = replaceNodeWithWidget(itemNode);

    -- 装备图标
    local equip = widget:clone();
    local equipIcon = findChildByName(equip, "icon");
    local equipIconPath = getItemIconPath(ItemM.query(self.equipId, "icon"));
    equipIcon:loadTexture(equipIconPath);
    equipNode:addChild(equip);

    local i = 1;
    for k, v in pairs(spellIds) do
        local icon = ItemM.query(v, "icon");
        local iconPath = getItemIconPath(icon);

        local spellNode = widget:clone();
        local iconNode = findChildByName(spellNode, "icon");

        iconNode:loadTexture(iconPath);

        self:registerIconTouchEvent(iconNode);
        iconNode.spellId = v;

        local item = findChildByName(self.CT, "item_" .. i);

        -- 如果是大地之门
        if 4005 == v then
            setGrayTransMode(iconNode, true);
        end

        item:removeAllChildren();
        item:addChild(spellNode);

        if SpellM.canCompoundSpell(v, 1) and 4005 ~= v then
            playBubbleAnima2(iconNode, false, 1, 0.8 , true);
        elseif not SpellM.canCompoundSpell(v, 1) and 4005 ~= v then
            iconNode:setOpacity(165);
        end
        i = i + 1;
    end
end

--
function UIChooseSpell:registerIconTouchEvent(iconNode)
    local function onClick(sender, eventType)
        -- 点击时的回调
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            -- 如果是大地之门
            if 4005 == sender.spellId then
                alert(getLocStr("cant_compound_spell"));
                return;
            end

            require "game/ui/form/risker_equip/UICompoundSpell";
             -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UICompoundSpell");
            local uiForm = UICompoundSpell.create(sender.spellId);
            UIMgr.getCurrentScene():addForm(uiForm);
        end
    end

    iconNode:addTouchEventListener(onClick);
end

-- 适配
function UIChooseSpell:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end